//
//  ZBOneSendMessage.m
//  BaseRACDemo
//
//  Created by 庄波 on 2018/3/28.
//  Copyright © 2018年 庄波. All rights reserved.
//

#import "ZBOneSendMessage.h"
#import "ZBOneSendMessageModel.h"
#import "ZBOneSendCell.h"
#import "ZBOneSendCellModel.h"
#import "ZBHTTPService+ResultData.h"
//语音识别view
#import "iflyMSC/IFlyRecognizerView.h"
#import "iflyMSC/IFlySpeechConstant.h"
#import "MHHTTPResponse.h"
#import "ZBLinkmanViewModel.h"
#import "UITextView+zb.h"

@interface ZBOneSendMessage ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)ZBOneSendMessageModel *viewModel;
@end

@implementation ZBOneSendMessage

- (instancetype)initWithViewModel:(ZBOneSendMessageModel *)viewModel {
    self = [super initWithNibName:@"ZBOneSendMessage" bundle:nil];
    if (self) {
        self.viewModel = viewModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setup];
}

- (void)setup{
    
    UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    btnRight.frame = CGRectMake(0, 0, ItemWidth, kNavigationBar_Height);
    [btnRight setImage:kIMG_Name(@"addresslist_write") forState:UIControlStateNormal];
    [btnRight setContentVerticalAlignment: UIControlContentVerticalAlignmentCenter];
    [btnRight setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
    [[btnRight rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        ZBLinkmanViewModel *linkViewModel = [[ZBLinkmanViewModel alloc] initWithServices:self.viewModel.services params:nil];
        linkViewModel.selectLinkman = ^(NSArray *arr) {
            NSArray *arrTemp = [[arr rac_sequence] map:^id _Nullable(NSString *value) {
                if (![self filter:value]) {
                    ZBOneSendCellModel *model = [[ZBOneSendCellModel alloc] initWithPhone:value];
                    return model;
                } else {
                    return nil;
                }
            }].array;
            NSMutableArray *aryData = @[].mutableCopy;
            [aryData addObjectsFromArray:arrTemp];
            [aryData addObjectsFromArray:self.viewModel.dataSource];
            self.viewModel.dataSource = [NSArray arrayWithArray:aryData];
        };
        [self.viewModel.services pushViewModel:linkViewModel animated:YES];
        
    }];
    
    
    // 注册cell
    self.tableViewXib.delegate = self;
    self.tableViewXib.dataSource = self;
    self.tableViewXib.tableFooterView = [[UIView alloc] init];
    //设置textField
    self.textFieldTop.borderStyle = UITextBorderStyleRoundedRect;
    self.textFieldTop.layer.cornerRadius = 4;
    self.textFieldTop.backgroundColor = KUIColorARGBString(@"#DBDBDB");
    self.textFieldTop.layer.masksToBounds = YES;
    self.textFieldTop.layer.borderColor = KUIColorARGBString(@"#DADADA").CGColor;
    self.textFieldTop.layer.borderWidth = 1.0f;
    
    self.textFieldBotoom.layer.cornerRadius = 5;
    self.textFieldBotoom.backgroundColor = KUIColorARGBString(@"#ffffff");
    self.textFieldBotoom.layer.masksToBounds = YES;
    self.textFieldBotoom.layer.borderColor = KUIColorARGBString(@"#DADADA").CGColor;
    self.textFieldBotoom.layer.borderWidth = 1.0f;
    
//    self.textFieldBotoom.text = @"您好，我是圆通快递员,您的快递已送到，请速来领取快递.";
    
    //创建语音听写的对象
    self.iflyRecognizerView = [[IFlyRecognizerView alloc] initWithCenter:self.view.center];//delegate需要设置，确保delegate回调可以正常返回
    self.iflyRecognizerView.delegate = self;
    
    if (iPhoneX) {
        self.top.constant = SafeAreaTopHeight;
        self.bottom.constant = SafeAreaTabbarHeight;
    }
}


-(void)bindViewModel{
    [super bindViewModel];
    
    @weakify(self)
    //绑定datasource
    [[RACObserve(self.viewModel, dataSource) deliverOnMainThread] subscribeNext:^(id x) {
        @strongify(self)
        //deliverOnMainThread包在主线程操作UI
        // 刷新数据
        [self reloadData];
        //重置btnALL
        [self.btnAll setSelected:NO];
    }];
    
    
    
    
    [[[[[RACSignal merge:@[RACObserve(self.textFieldTop, text),self.textFieldTop.rac_textSignal]] filter:^BOOL(NSString * _Nullable value) {
        return [value isMobileNumber];
    }] doNext:^(NSString * _Nullable x) {
        @strongify(self)
        self.textFieldTop.text = @"";
        [self.textFieldTop resignFirstResponder];
    }] map:^id _Nullable(NSString * _Nullable value) {
         if (![self filter:value]) {
             ZBOneSendCellModel *model = [[ZBOneSendCellModel alloc] initWithPhone:value];
             model.isSeleled = YES;
             return model;
         }else{
             [CustomMBHUD showErrorWithStatus:@"已存在!"];
             return nil;
         }
    }] subscribeNext:^(ZBOneSendCellModel * _Nullable x) {
        if (!x) {
            return ;
        }
        @strongify(self)

        
        NSMutableArray *aryData = @[].mutableCopy;
        [aryData addObjectsFromArray:self.viewModel.dataSource];
        [aryData insertObject:x atIndex:0];
        self.viewModel.dataSource = [NSArray arrayWithArray:aryData];
        
        NSMutableArray *aryData2 = @[].mutableCopy;
        [aryData2 addObjectsFromArray:self.viewModel.arySeleled];
        [aryData2 insertObject:x atIndex:0];
        self.viewModel.arySeleled = [NSArray arrayWithArray:aryData2];
    }];
    //选中
    
    [[[[RACObserve(self, viewModel.arySeleled) skip:1] filter:^BOOL(NSArray* value) {
        self.labCount.text = [NSString stringWithFormat:@"合计：%d条",value.count];
        [self.btnAll setSelected:NO];
        return value.count!=0;
    }] map:^id _Nullable(NSArray* value) {
        return value.count == self.viewModel.dataSource.count?@1:@0;
    }] subscribeNext:^(id  _Nullable x) {
        [self.btnAll setSelected:[x boolValue]];
    }];
    //全选
    [[self.btnAll rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIButton * _Nullable x) {
        if (!x.selected) {
            self.viewModel.arySeleled = [NSArray arrayWithArray:self.viewModel.dataSource];
        }else{
            self.viewModel.arySeleled = nil;
            [x setSelected:!x.selected];
        }
        [[[self.viewModel.dataSource rac_sequence] map:^id _Nullable(ZBOneSendCellModel *value) {
            value.isSeleled = x.selected;
            return value;
        }]array];
    }];
    //发送
    [[self.btnSend rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (self.viewModel.arySeleled.count == 0) {
            [CustomMBHUD showErrorWithStatus:@"请选择发送号码"];
        }else{
            
            NSArray *aryPhone = [[[self.viewModel.arySeleled rac_sequence] map:^id _Nullable(id  _Nullable value) {
                ZBOneSendCellModel*model = value;
                return model.phone;
            }]array];
            ZBUserOwn *own = [self.viewModel.services.client currentUser];
            RACSignal *sendSigal= [self.viewModel.services.client sendMessagteWithPhone:aryPhone withTemplate:self.textFieldBotoom.text withToken:own.token];
            [sendSigal subscribeNext:^(id  _Nullable x) {
                MHHTTPResponse *response = x;
                if (response.code == MHHTTPResponseCodeSuccess) {
                    [CustomMBHUD showErrorWithStatus:@"发送成功"];
                }else{
                    [CustomMBHUD showErrorWithStatus:response.msg];
                }
            }];
            
            [sendSigal subscribeError:^(NSError * _Nullable error) {
                [CustomMBHUD showErrorWithStatus:error.description];
            }];
        }
    }];
    
    //请求短信模版
    [self.viewModel.templateCommand execute:([self.viewModel.services.client currentUser]).token];
    //绑定底部textView数据
    RAC(self.textFieldBotoom,text) = RACObserve(self, viewModel.textStr);
//    [[RACObserve(self.textFieldBotoom, text) ignore:@""] subscribeNext:^(id  _Nullable x) {
//        [self.textFieldBotoom contentSizeToFit:kSetting.font_13];
//    }];
    
#warning  这个方法为什么在viewModel就可以呢
//    RAC(self.textFieldBotoom,text) = self.viewModel.templateCommand.executionSignals.switchToLatest;
#warning 为什么这里不走呢？
    [self.viewModel.templateCommand.executionSignals subscribeNext:^(id  _Nullable x) {
        //
    }];
    [self.viewModel.templateCommand.executionSignals subscribeError:^(NSError * _Nullable error) {
        //
    }];
    
    

}

- (BOOL)filter:(NSString *)str{
    NSArray *aryData = [[[self.viewModel.dataSource rac_sequence] filter:^BOOL (id value){
        ZBOneSendCellModel *model = value;
        return [model.phone isEqualToString:str];
    }] array];
    return aryData.count>0?YES:NO;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

//语音识别
- (IBAction)voiceStar:(id)sender {
    [_iflyRecognizerView setParameter: @"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];

    //设置结果数据格式，可设置为json，xml，plain，默认为json。
    [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];

    [_iflyRecognizerView start];

    NSLog(@"start listenning...");
}

/** 识别结果回调方法
 @param resultArray 结果列表
 @param isLast YES 表示最后一个，NO表示后面还有结果
 */
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast {
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    NSString *someString = [NSString stringWithFormat:@"%@",result];
    if ([someString hasPrefix:@"，"]) {
        someString = [someString substringFromIndex:1];
    }
    else if ([someString hasSuffix:@"。"]) {
        someString = [someString substringToIndex:someString.length - 1];
    }
    else if ([someString isEqualToString:@""]) {
        
    }
    else {
        NSInteger iiiii = [someString integerValue];
        self.textFieldTop.text = [NSString stringWithFormat:@"%@%ld",self.textFieldTop.text,(long)iiiii];
    }
    
}

/** 识别结束回调方法
 @param error 识别错误
 */
- (void)onError:(IFlySpeechError *)error {
    
    NSLog(@"errorCode:%@",error);
}

#pragma mark - sub class can override it
- (UIEdgeInsets)contentInset{
    return UIEdgeInsetsMake(SafeAreaTopHeight, 0, 0, 0);
}

/// reload tableView data
- (void)reloadData{
    [self.tableViewXib reloadData];
}

/// duqueueReusavleCell
- (ZBOneSendCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
    return [ZBOneSendCell cellWithTableView:tableView];
}


#pragma mark - 辅助方法
- (void)_requestDataCompleted{
    NSUInteger count = self.viewModel.dataSource.count;
    /// CoderMikeHe Fixed: 这里必须要等到，底部控件结束刷新后，再来设置无更多数据，否则被叠加无效
    if (self.viewModel.shouldEndRefreshingWithNoMoreData && count%self.viewModel.perPage) [self.tableViewXib.mj_footer endRefreshingWithNoMoreData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.viewModel.shouldMultiSections) return self.viewModel.dataSource ? self.viewModel.dataSource.count : 0;
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.viewModel.shouldMultiSections) return [self.viewModel.dataSource[section] count];
    return self.viewModel.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZBOneSendCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:@"UITableViewCellOne" forIndexPath:indexPath];
    // fetch object
    id object = nil;
    if (self.viewModel.shouldMultiSections) object = self.viewModel.dataSource[indexPath.section][indexPath.row];
    if (!self.viewModel.shouldMultiSections) object = self.viewModel.dataSource[indexPath.row];
    /// bind model
    [self configureCell:cell atIndexPath:indexPath withObject:(id)object];
    
    [[[cell.btnSelected rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
        //点击事件
        ZBOneSendCellModel *model = object;
        model.isSeleled = !cell.btnSelected.selected;
        if (model.isSeleled) {
            NSMutableArray *mAryData = @[].mutableCopy;
            [mAryData addObjectsFromArray:self.viewModel.arySeleled];
            [mAryData addObject:model];
            self.viewModel.arySeleled = [NSArray arrayWithArray:mAryData];
        }else{ 
            NSMutableArray *mAryData = @[].mutableCopy;
            [mAryData addObjectsFromArray:self.viewModel.arySeleled];
            NSArray *ary = [[[mAryData rac_sequence] filter:^BOOL (ZBOneSendCellModel *value){
                return ![value.phone isEqualToString:model.phone];
            }] array];
            self.viewModel.arySeleled = [NSArray arrayWithArray:ary];
        }
    }];
    
    [[[cell.btnDelele rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
         ZBOneSendCellModel *model = object;

        NSArray *aryDataTwo = [[[self.viewModel.dataSource rac_sequence] filter:^BOOL(id  _Nullable value) {
            ZBOneSendCellModel *modeValue = value;
            return ![model.phone isEqualToString:modeValue.phone];
        }]  array];
        self.viewModel.dataSource = [NSArray arrayWithArray:aryDataTwo];
        
        NSArray *aryData = [[[self.viewModel.arySeleled rac_sequence] filter:^BOOL(id  _Nullable value) {
            ZBOneSendCellModel *modeValue = value;
            return ![model.phone isEqualToString:modeValue.phone];
        }] array];
        self.viewModel.arySeleled = [NSArray arrayWithArray:aryData];
        

    }];
    return cell;
}

/// 绑定数据
- (void)configureCell:(ZBOneSendCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object{
        [cell bindViewModel:object];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // execute commond
    
    ZBOneSendCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    id object;
    if (self.viewModel.shouldMultiSections) object = self.viewModel.dataSource[indexPath.section][indexPath.row];
    if (!self.viewModel.shouldMultiSections) object = self.viewModel.dataSource[indexPath.row];
    ZBOneSendCellModel *model = object;
    model.isSeleled = !cell.btnSelected.selected;
    if (model.isSeleled) {
        NSMutableArray *mAryData = @[].mutableCopy;
        [mAryData addObjectsFromArray:self.viewModel.arySeleled];
        [mAryData addObject:model];
        self.viewModel.arySeleled = [NSArray arrayWithArray:mAryData];
    }else{
        NSMutableArray *mAryData = @[].mutableCopy;
        [mAryData addObjectsFromArray:self.viewModel.arySeleled];
        NSArray *ary = [[[mAryData rac_sequence] filter:^BOOL (ZBOneSendCellModel *value){
            return ![value.phone isEqualToString:model.phone];
        }] array];
        self.viewModel.arySeleled = [NSArray arrayWithArray:ary];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
